package system

import (
	"encoding/json"
	"github.com/gin-gonic/gin"
	"log"
	"woo-server/coms/structs"
	"woo-server/coms/utils"
	"woo-server/models/api"
	"woo-server/models/db/system"
)

// 结构
type Service struct {
	*structs.Common
}

// 初始化
func NewRoleService(com *structs.Common) *Service {
	return &Service{com}
}

// 角色列表
func (s *Service) GetList(context *gin.Context) *api.ResultEntity {

	search := context.Query("search")
	page := structs.SetInt(context.Query("page"))
	pageSize := structs.SetInt(context.Query("pageSize"))
	Model := system.NewRole(s.Common)
	list, total := Model.GetListAndTotal(search, page, pageSize)
	MenuModel := system.NewMenus(s.Common)
	var RoleList structs.ROLE
	var ResultList []structs.ROLE
	for _, v := range list {
		RoleList.AdminRoleId = v.AdminRoleId
		RoleList.Name = v.Name
		RoleList.AdminMenuId = v.AdminMenuId
		RoleList.Describe = v.Describe
		if v.AdminRoleId != 1 {
			var adminMenuId []int
			err := json.Unmarshal([]byte("["+v.AdminMenuId+"]"), &adminMenuId)
			if err != nil {
				log.Fatal(err)
			}
			treelist, _ := MenuModel.GetRoleMenu("admin_menu_id in ?", adminMenuId, true)
			RoleList.AdminMenus = treelist
		} else {
			treelist, _ := MenuModel.GetAllMenu(true)
			RoleList.AdminMenus = treelist
		}
		ResultList = append(ResultList, RoleList)
		//fmt.Println(MenuModel.MakeRoleMenuInSelect(Menulist, 0))
	}
	result := map[string]interface{}{"list": ResultList, "total": total}
	return api.SuccessToJson(result, "角色列表获取成功!")
}

// 当前用户信息
func (s *Service) GetConfig(context *gin.Context) *api.ResultEntity {
	Model := system.NewRole(s.Common)
	data := Model.GetConfig()
	return api.SuccessToJson(data, "获取角色配置成功!")
}

func (s *Service) PostSave(context *gin.Context) *api.ResultEntity {
	Name := context.PostForm("Name")
	if Name == "" {
		return api.Error("角色名称不能为空!")
	}
	Model := system.NewRole(s.Common)

	Model.Name = Name
	Model.AdminMenuId = context.PostForm("AdminMenuId")
	Model.Describe = context.PostForm("Describe")
	AdminRoleId := uint64(structs.SetInt(context.PostForm("AdminRoleId")))
	var err error
	if AdminRoleId == 0 {

		// 基础参数
		Model.SetCreateInfo(s.Claim.UserId)
		// 执行创建
		err = Model.Create()
	} else {
		Model.AdminRoleId = AdminRoleId
		Model.SetUpdateInfo(s.Claim.UserId)
		err = Model.Save()

	}
	if err != nil {
		// 日志
		utils.LogError("新增角色报错:%s", err.Error())
		return api.Error(err.Error())
	}
	return api.Success("success")
}

func (s *Service) Delete(context *gin.Context) *api.ResultEntity {
	//context.Param()
	// 接收POST参数
	AdminRoleId := context.PostForm("AdminRoleId")
	// 校验参数
	if AdminRoleId == "" {
		return api.Error("ID不能为空!")
	}
	if AdminRoleId == "1" {
		api.Error("无法删除超级管理员")
	}
	// 实例化数据库
	Model := system.NewRole(s.Common)
	// 执行删除
	Model.AdminRoleId = uint64(structs.SetInt(AdminRoleId))
	// 删除数据
	err := Model.Delete()
	if err != nil {
		utils.LogError("删除角色报错:%s", err.Error())
		return api.Error(err.Error())
	}
	return api.Success("删除成功")
}
